//
//  MeetingDetailViewController.m
//  发布会
//
//  Created by chen wei on 13-5-21.
//  Copyright (c) 2013年 Hq. All rights reserved.
//

#import "MeetingDetailViewController.h"
#import "RequestServer.h"
#import <CommonCrypto/CommonDigest.h>
#import "ASIHTTPRequest.h"
#import "BSAppDelegate.h"
#import "YLLabel.h"
#import "SBJsonWriter.h"
#import "JSON.h"
#import "MSCommentsCell.h"
#import "MSCommentsViewController.h"
#import "MSWriteCommentViewController.h"
#import "MSImageView.h"
#import "readfileTool.h"
#import "HtmlCell.h"

@interface MeetingDetailViewController ()<MSCommentFinishedDelegete>
{
    NSDictionary *dictionary;
}
//@property(nonatomic, retain)UIView*     toolBar;
@property(nonatomic, retain)UITableView*     tableView;
@end

@implementation MeetingDetailViewController

- (id)initWithStyle:(UITableViewStyle)style withContentId:(NSDictionary*)diction
{
    if ([super init] != nil) {
        dictionary = diction;
        [dictionary retain];
    }
    return self;
}

#pragma mark - uitableview
-(void)initTableView {
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStylePlain];
    [self.tableView setDelegate:self];
	[self.tableView setDataSource:self];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	self.tableView.backgroundColor = [UIColor colorWithHexString:@"f0f0f0"];
	self.tableView.backgroundView.alpha = 0.5;
	self.tableView.autoresizingMask = AutoresizingFull;
    self.tableView.delegate = self;
	[self.view addSubview:self.tableView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    db = [[SQLite alloc] initWithDbName:[defaults objectForKey:@"CurrentDataBaseName"]];
    
    self.title = @"详情";
    self.view.backgroundColor = [UIColor colorWithHexString:@"f0f0f0"];
    [self initTableView];
    
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setFrame:CGRectMake(12, 6, 28, 28)];
    [backButton setImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
    backButton.backgroundColor = [UIColor clearColor];
    [backButton addTarget:self action:@selector(Goback) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
    
    if (self.tag == 1) {
        UIButton *add=[UIButton buttonWithType:UIButtonTypeCustom];
        add.frame=CGRectMake(0,0,40,30);
        [add setTitle:@"回复" forState:UIControlStateNormal];
        [add addTarget:self action:@selector(writeComment) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBar=[[UIBarButtonItem alloc]initWithCustomView:add];
        
        self.navigationItem.rightBarButtonItem =rightBar;
        [rightBar release];
    }
    NSString *get_menus = nil;
    if (self.tag == 1) {
        get_menus =[NSString stringWithFormat: @"select * from AnnounceRecordsTable where id = '%@'",[dictionary objectForKey:@"id"]];
    }else if (self.tag == 2){
        get_menus =[NSString stringWithFormat: @"select * from huiyi where id = '%@'",[dictionary objectForKey:@"id"]];
    }
    NSArray *array = [NSArray arrayWithArray:[db querryTable:get_menus]];
    if (0==[array count]||[[[array objectAtIndex:0] objectForKey:@"context"] isEqualToString:@""]) {
        if (self.tag == 1) {
            NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:[dictionary objectForKey:@"id"],@"newsId",nil];
            [[RequestServer instance] doActionAsync:0 withAction:@"com.haoqee.businessSchool.client.action.NewsRemindAction$getNewRemindInfo" withParameters:para withDelegate:self];
            tag = 1;
        }else if (self.tag == 2){
            NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:[dictionary objectForKey:@"id"],@"meetingId",nil];
            [[RequestServer instance] doActionAsync:0 withAction:@"com.haoqee.businessSchool.client.action.MeetingAction$getNewMeetingInfo" withParameters:para withDelegate:self];
            tag = 1;
        }
       
    } else {
        dictionary = [array objectAtIndex:0];
        title = [dictionary objectForKey:@"title"];
        [title retain];
        author = [dictionary objectForKey:@"createUser"];
        [author retain];
        time = [dictionary objectForKey:@"createDate"];
        [time retain];
        
        content = [dictionary objectForKey:@"context"];
        [content retain];
        files = [[NSArray alloc] initWithArray:(NSArray*)[[dictionary objectForKey:@"files"] JSONValue]];
        
        [self.tableView reloadData];
    }
    
    
//    title = [dictionary objectForKey:@"title"];
//    [title retain];
//    author = [dictionary objectForKey:@"createUser"];
//    [author retain];
//    time = [dictionary objectForKey:@"createDate"];
//    [time retain];
//  
//    content = [dictionary objectForKey:@"context"];
//    [content retain];
//    files = [[NSArray alloc] initWithArray:(NSArray*)[[dictionary objectForKey:@"files"] JSONValue]];
//    
//    [self.tableView reloadData];
  
}

- (void)requestFinished:(NSNumber *)code withMessage:(NSString *)message withData:(id)data
{
    if (tag == 1) {
        if (code == 0) {
            NSString *contextString = [NSString stringWithFormat:@"%@",[data objectForKey:@"context"]];
            NSString *createDateString = [NSString stringWithFormat:@"%@",[data objectForKey:@"createDate"]];
            NSString *titleString = [NSString stringWithFormat:@"%@",[data objectForKey:@"title"]];
            NSString *closeTimeString = [NSString stringWithFormat:@"%@",[data objectForKey:@"closeTime"]];
            NSString *createUserString = [NSString stringWithFormat:@"%@",[data objectForKey:@"createUser"]];
            NSString *upDateString = [NSString stringWithFormat:@"%@",[data objectForKey:@"upDate"]];
            
            SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
            NSString *fileString = [jsonWriter stringWithObject:[data  objectForKey:@"files"]];
            [jsonWriter release];
            
            NSString *execute = nil;
            if (self.tag == 1) {
               execute = [NSString stringWithFormat:@"update AnnounceRecordsTable set title = '%@',context = '%@',closeTime = '%@',createUser = '%@',createDate = '%@',upDatetime = '%@',files = '%@' where id = '%@'",titleString,contextString,closeTimeString,createUserString,createDateString,upDateString,fileString, [dictionary objectForKey:@"id"]];
            }else{
              execute  = [NSString stringWithFormat:@"update huiyi set title = '%@',context = '%@',closeTime = '%@',createUser = '%@',createDate = '%@',upDatetime = '%@',files = '%@' where id = '%@'",titleString,contextString,closeTimeString,createUserString,createDateString,upDateString,fileString, [dictionary objectForKey:@"id"]];
            }
            
            if (![db updateTable:execute]) {
                NSLog(@"数据插入有误!");
            }
            NSString *get_menus = nil;
            if (self.tag == 1) {
                get_menus =[NSString stringWithFormat: @"select * from AnnounceRecordsTable where id = '%@'",[dictionary objectForKey:@"id"]];
            }else{
                get_menus =[NSString stringWithFormat: @"select * from huiyi where id = '%@'",[dictionary objectForKey:@"id"]];
            }
            NSArray *array = [NSArray arrayWithArray:[db querryTable:get_menus]];
            if ([array count] > 0) {
                NSDictionary *dic = (NSDictionary*)[array objectAtIndex:0];

                title = [dic objectForKey:@"title"];
                [title retain];
                author = [dic objectForKey:@"createUser"];
                [author retain];
                time = [dic objectForKey:@"createDate"];
                [time retain];
                
                content = [dic objectForKey:@"context"];
                [content retain];
                files = [[NSArray alloc] initWithArray:(NSArray*)[[dic objectForKey:@"files"] JSONValue]];
            }

            [self.tableView reloadData];
       
           
            
        }else if ([code intValue]== 1) {
            ShowMessage(message);
        }else{
            NSLog(@"请求失败");
        }
        
    }
}


-(void)Goback
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([files count] > 0) {
        return  3;
    }else{
        return 2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    if (section == 1) {
        return 1;
    }
    if (section == 2) {
        return [files count];
    }
   
    return 0;
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return nil;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 70;
    }
    if (indexPath.section == 2) {
        return 50;
    }
    if (indexPath.section == 1) {
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        return cell.frame.size.height;
    }
    return 50;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    if (indexPath.section == 0) {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell* cell = nil;//
        
        if (nil == cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
        
        UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        titleView.backgroundColor  = [UIColor clearColor];
        
        
        titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 2, self.view.frame.size.width-16, 50)];
        titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
        titleLabel.numberOfLines = 0;
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.text = title;
        titleLabel.textAlignment = NSTextAlignmentLeft;
        titleLabel.font = [UIFont boldSystemFontOfSize:20];
        [titleView addSubview:titleLabel];
        
        
        timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 49, self.view.frame.size.width, 18)];
        timeLabel.textColor = [UIColor grayColor];
        timeLabel.textAlignment = NSTextAlignmentLeft;
        timeLabel.font = [UIFont fontWithName:@"Helvetica" size:13];
        if (!author&&time) {
            timeLabel.text = [NSString stringWithFormat:@"%@", time];
        }
        if (!time&&author) {
            timeLabel.text = [NSString stringWithFormat:@"%@", author];
        }
        if (time&&author) {
            timeLabel.text = [NSString stringWithFormat:@"%@   %@", author, time];
        }
        if (time&&author) {
            timeLabel.text = [NSString stringWithFormat:@"%@   %@", author, time];
        }
        timeLabel.backgroundColor = [UIColor clearColor];
        [titleView addSubview:timeLabel];
        [cell.contentView addSubview:titleView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIImageView *bgImageLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line.png"]];
        bgImageLine.frame = CGRectMake(0, 69, self.view.width, 2);
        [cell addSubview:bgImageLine];
        
        return cell;
    }else if (indexPath.section == 2){
        
        static NSString *CellIdentifier = @"Cellfiel";
        UITableViewCell* cell = nil;//
        if (nil == cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
        if (self.tag == 1) {
            NSString *filename = [[files objectAtIndex:indexPath.row] objectForKey:@"originalName"];
            UIImageView *filebg = [[UIImageView alloc]initWithFrame:CGRectMake(26, 0, 267, 50)];
            [filebg setImage:[UIImage imageNamed:@"preview.png"]];
            
            
            UIImageView *filetubiao = [[UIImageView alloc]initWithFrame:CGRectMake(5, 7, 35, 35)];
            [filetubiao setImage:[UIImage imageNamed:@"preview.png"]];
            [cell addSubview:filetubiao];
            
            if ([filename hasSuffix:@".pdf"]) {
                filetubiao.image = [UIImage imageNamed:@"pdf.png"];
            }else  if ([filename hasSuffix:@".txt"]) {
                filetubiao.image = [UIImage imageNamed:@"txt.png"];
            }else  if ([filename hasSuffix:@".ppt"] ||[filename hasSuffix:@".pptx"]) {
                filetubiao.image = [UIImage imageNamed:@"ppt.png"];
            }else  if ([filename hasSuffix:@".docx"] ||[filename hasSuffix:@".doc"]) {
                filetubiao.image = [UIImage imageNamed:@"word.png"];
            }else if ([filename hasSuffix:@".xlsx"] ||[filename hasSuffix:@".xls"]) {
                filetubiao.image = [UIImage imageNamed:@"excel.png"];
            }else if ([filename hasSuffix:@".jpg"]) {
                filetubiao.image = [UIImage imageNamed:@"jpg.png"];
            }else{
                filetubiao.image = [UIImage imageNamed:@"png.png"];
            }
            [filebg addSubview:filetubiao];
            
            UILabel * file = [[UILabel alloc]initWithFrame:CGRectMake(50, 0, 210, 50)];
            file.backgroundColor = [UIColor clearColor];
            file.lineBreakMode = NSLineBreakByCharWrapping;
            file.numberOfLines = 0;
            file.font =  [UIFont fontWithName:@"Helvetica" size:18.0];
            file.text =filename;
            [filebg addSubview:file];
            
            [cell addSubview:filebg];
            [filebg release];
            [filetubiao release];
            [file release];
        }else{
            UILabel *begintime = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 310, 25)];
            begintime.backgroundColor = [UIColor clearColor];
            begintime.textAlignment = NSTextAlignmentLeft;
            begintime.font = [UIFont fontWithName:@"Helvetica" size:12.0];
            begintime.text = [NSString stringWithFormat:@"开始时间：%@",[[files objectAtIndex:indexPath.row] objectForKey:@"startDate"]];
            [cell addSubview:begintime];
            [begintime release];
            
            UILabel *endtime = [[UILabel alloc]initWithFrame:CGRectMake(5, 25, 310, 25)];
            endtime.backgroundColor = [UIColor clearColor];
            endtime.textAlignment = NSTextAlignmentLeft;
            endtime.font = [UIFont fontWithName:@"Helvetica" size:12.0];
            endtime.text = [NSString stringWithFormat:@"结束时间：%@",[[files objectAtIndex:indexPath.row] objectForKey:@"startDate"]];
            [cell addSubview:endtime];
            [endtime release];
            
        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell* cell = nil;//
        HtmlCell *htmlcell = nil;
        if (nil == cell) {
            htmlcell = [[HtmlCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
        htmlcell.row = indexPath.row;
        htmlcell.section = indexPath.section;
        [htmlcell.webView loadHTMLString:content baseURL:nil];
        htmlcell.userInteractionEnabled = YES;
        cell = htmlcell;
        
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 2) {
        NSString *url = [NSString stringWithFormat:@"%@",[[files objectAtIndex:indexPath.row] objectForKey:@"address"]];
        readfileTool *fileview = [[readfileTool alloc]initWithUrl:url];
        [self.navigationController pushViewController:fileview animated:YES];
    }
    
}

- (void)scale:(UIButton*)sender
{
//    int i = [sender tag];
//    UIImage *image = [photos objectAtIndex:i];
//    MSImageView *zoomScrollView = [[MSImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, image.size.height*self.view.frame.size.width/image.size.width)];
//    zoomScrollView.imageView.image = image;
//    BSAppDelegate *app = (BSAppDelegate*)[[UIApplication sharedApplication]delegate];
//    [app.window.rootViewController.view addSubview:zoomScrollView];
}



#pragma mark -- 按钮事件 --
- (void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)gotoComment
{
    MSCommentsViewController *viewController = [[MSCommentsViewController alloc] initWithContentId:[dictionary objectForKey:@"id"]];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)writeComment
{
    MSWriteCommentViewController *viewController = [[MSWriteCommentViewController alloc] initWithContentId:[dictionary objectForKey:@"id"]];
    viewController.delegate = self;
//    [self presentModalViewController:viewController animated:YES];
    [self presentViewController:viewController animated:YES completion:^(void) {}];
}

- (void)commentWriteFinished
{
    [self gotoComment];
}

@end
